package com.xuecheng.manage_media.service;

import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_media.dao.MediaFileRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

@Service
public class MediaFIleService {

    @Autowired
    MediaFileRepository mediaFileRepository;

    public QueryResponseResult<MediaFile> getList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        //定义文件对象
        MediaFile mediaFile=new MediaFile();
        if(queryMediaFileRequest == null){
            queryMediaFileRequest = new QueryMediaFileRequest();
        }
        //条件查询匹配器
        ExampleMatcher matcher=ExampleMatcher.matching()
                //tag与fileOriginalName模糊匹配，处理状态精确匹配
                .withMatcher("tag",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("fileOriginalName",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("processStatus",ExampleMatcher.GenericPropertyMatchers.exact());//如果不设置匹配器，则字段默认为精确匹配
        //查询条件对象
        if(StringUtils.isNotEmpty(queryMediaFileRequest.getTag())){
            mediaFile.setTag(queryMediaFileRequest.getTag());
        }
        if(StringUtils.isNotEmpty(queryMediaFileRequest.getFileOriginalName())){
            mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
        }
        if(StringUtils.isNotEmpty(queryMediaFileRequest.getProcessStatus())){
            mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
        }
        //定义Example实例
        Example<MediaFile> example=Example.of(mediaFile,matcher);
        //分页参数
        if(page<=0){
            page=1;
        }
        page=page-1;
        if(size<=0){
            size=10;
        }
        Pageable pageable=new PageRequest(page,size);
        //分页查询
        Page<MediaFile>  mediaFiles= mediaFileRepository.findAll(example,pageable);
        QueryResult<MediaFile> mediaFileQueryResult=new QueryResult<>();
        mediaFileQueryResult.setList(mediaFiles.getContent());
        mediaFileQueryResult.setTotal(mediaFiles.getTotalPages());
        return new QueryResponseResult<>(CommonCode.SUCCESS,mediaFileQueryResult);
    }
}
